<?php
namespace app\common\model;


class Signin extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_signin';
    // 主键ID
    protected $pk = 'sign_id';

//    获取一条数据
    function    getOne($where=[1], $item='*')
    {
        $rs = $this
            ->field($item)
            ->where($where)
            ->find();

        return $rs;
    }

    // 获取用户当周所有签到信息
    public function signinfo($userid)
    {
//        var_dump($userid);
        $sdefaultDate = date("Y-m-d");
        //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
        $first=1;
        //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $w = date('w',strtotime($sdefaultDate));
        //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
        $week_start = strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days');
        //本周结束日期
        $week_end = strtotime(date('Y-m-d',$week_start)." +7 days");
        $signinfo = $this
            ->where('user_id','=',$userid)
            ->where('add_time','between','"'.$week_start.','.$week_end.'"')
            ->select();
        return $signinfo;
    }

    // 用户签到操作
    public function usersignin($userid,$userinfo,$intergal = 20)
    {
        $userModel = new User();
        $time = time();
        $twhere = [
            ['user_id','=',$userid],
            ['date','=',date('Y-m-d',$time)]
        ];
        $today = $this->getOne($twhere);
        if(!empty($today)){
            $this->setError(-1,'您今天已签到');
            return false;
        }
        $where = [
            ['user_id','=',$userid],
            ['date','=',date('Y-m-d',strtotime(" -1 days"))]
        ];
//        var_dump($where);die;
        $yesterday = $this->getOne($where);
//        var_dump($yesterday);die;
        if(!$yesterday){
            $param['sign_days'] = 1;
        } else {
            $param['sign_days'] = $userinfo['sign_days'] + 1;
        }
        $param['growth_coin'] = $userinfo['growth_coin'] + $intergal;
        $data = [
            "user_id" => $userid,
            "integral" => $intergal,
            "date" => date('Y-m-d',$time),
            "add_time" => $time,
        ];
        $userModel->startTrans();
        $userwhere = ['user_id' => $userid];
        $rs = $userModel->allowField(true)->save($param, $userwhere);
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            $userModel->rollback();
            return false;
        }
//        var_dump(123);die;
        $result = $this->allowField(true)->save($data);
        if($result === false){
            $this->setError(-1,'操作失败了');
            $userModel->rollback();
            return false;
        }
        $userModel->commit();
        return true;
    }

}